package com.lmm.cg.zjgcg.pages.ocr;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import com.lmm.cg.zjgcg.R;
import com.lmm.cg.zjgcg.camera.CameraInterface;
import com.lmm.cg.zjgcg.camera.CameraParaUtil;
import com.lmm.cg.zjgcg.camera.CameraPreview;
import com.lmm.cg.zjgcg.camera.utils.BitmapUtils;
import com.lmm.cg.zjgcg.camera.utils.DialogUtil;
import com.lmm.cg.zjgcg.camera.utils.XPermissionUtils;
import com.lmm.cg.zjgcg.pages.AppBaseActivity;
import com.lmm.cg.zjgcg.pages.ReactNativePresent;
import com.lmm.cg.zjgcg.pages.rnplugins.UploadCallBack;
import com.lmm.dresswisdom.lmmframe.util.LogUtils;
import com.lmm.dresswisdom.lmmframe.util.ToastUtils;

import java.io.File;

import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 车牌识别
 */
@Route(path = "/page/ocr")
public class OcrPhotoActivity extends AppBaseActivity implements CameraInterface.CameraListener {

    private final String TAG = "SydCamera";
    private final int PERMISSION_REQUEST_CODE_CAMERA = 0x02;
    private final int PERMISSION_REQUEST_CODE_STORAGE = 0x03;
    private FrameLayout preview;
    private CameraPreview mSurfaceView;
    private ImageView img_take_picture;
    private ImageView img_exit;
    private OrientationEventListener mOrientationListener;
    private int cameraOrientation = 0;
    private int picQuality;
    private int picWidth;
    private int previewWidth;
    private int pictureSize;
    private final String rootPath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "cg" + File.separator;
    ReactNativePresent mPresent;

    @Autowired(name = "type")
    public String uploadType = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ARouter.getInstance().inject(this);
        setContentView(R.layout.activity_ocr);

        picQuality = CameraParaUtil.defaultPicQuality;
        picWidth = CameraParaUtil.defaultPicWidth;
        previewWidth = CameraParaUtil.defaultPreviewWidth;
        pictureSize = 0;

        mPresent = new ReactNativePresent();
        initView();
        initEvent();
        checkCameraPermission();
        checkSdPermission();

    }

    private void initView() {
        preview = (FrameLayout) findViewById(R.id.camera_preview);
        img_take_picture = (ImageView) findViewById(R.id.img_take_picture);
        img_exit = (ImageView) findViewById(R.id.img_exit);
    }

    private void initCameraView() {
        CameraInterface.getInstance().setMinPreViewWidth(previewWidth);
        CameraInterface.getInstance().setMinPicWidth(picWidth);
        CameraInterface.getInstance().setCameraListener(this);
        mSurfaceView = new CameraPreview(this);
        mSurfaceView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                CameraInterface.getInstance().focusOnTouch((int) event.getX(), (int) event.getY(), preview);
                return false;
            }
        });
        preview.addView(mSurfaceView);
    }

    private void initEvent() {
        //拍照
        img_take_picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CameraInterface.getInstance().takePicture();
            }
        });

        //退出拍照
        img_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancelTakePhoto();
            }
        });

        //监听手机旋转角度
        mOrientationListener = new OrientationEventListener(this) {
            @Override
            public void onOrientationChanged(int orientation) {
                cameraOrientation = orientation;
            }
        };
    }

    private void checkCameraPermission() {
        XPermissionUtils.requestPermissions(this, PERMISSION_REQUEST_CODE_CAMERA, new String[]{Manifest.permission.CAMERA},
                new XPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        Log.i(TAG, "checkCameraPermission onPermissionGranted");
                        if (CameraInterface.getInstance().getCamera() == null) {
                            Log.e(TAG, "checkCameraPermission getCamera() == null");
                            DialogUtil.showPermissionDeniedDialog(OcrPhotoActivity.this, "相机");
                        } else {
                            initCameraView();
                        }
                    }

                    @Override
                    public void onPermissionDenied(final String[] deniedPermissions, boolean alwaysDenied) {
                        Toast.makeText(OcrPhotoActivity.this, "获取相机权限失败", Toast.LENGTH_SHORT).show();
                        if (alwaysDenied) { // 拒绝后不再询问 -> 提示跳转到设置
                            DialogUtil.showPermissionDeniedDialog(OcrPhotoActivity.this, "相机");
                        } else {    // 拒绝 -> 提示此公告的意义，并可再次尝试获取权限
                            DialogUtil.showPermissionRemindDiaog(OcrPhotoActivity.this, "相机", deniedPermissions, PERMISSION_REQUEST_CODE_CAMERA);
                        }
                    }
                });
    }

    private void checkSdPermission() {
        XPermissionUtils.requestPermissions(this, PERMISSION_REQUEST_CODE_STORAGE, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                new XPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        Log.i(TAG, "checkSdPermission onPermissionGranted");
                    }

                    @Override
                    public void onPermissionDenied(final String[] deniedPermissions, boolean alwaysDenied) {
                        Log.i(TAG, "checkSdPermission onPermissionDenied");
                        if (alwaysDenied) { // 拒绝后不再询问 -> 提示跳转到设置
                            DialogUtil.showPermissionDeniedDialog(OcrPhotoActivity.this, "文件存储");
                        } else {    // 拒绝 -> 提示此公告的意义，并可再次尝试获取权限
                            DialogUtil.showPermissionRemindDiaog(OcrPhotoActivity.this, "文件存储", deniedPermissions, PERMISSION_REQUEST_CODE_CAMERA);
                        }
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mOrientationListener.enable();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mOrientationListener != null)
            mOrientationListener.disable();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                cancelTakePhoto();
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void cancelTakePhoto() {
        Intent intent = new Intent();
        setResult(RESULT_CANCELED, intent);
        finish();
    }

    @Override
    public void onTakePictureSuccess(File pictureFile) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        Bitmap bitmap = BitmapUtils.rotateBitmap(BitmapFactory.decodeFile(pictureFile.getPath(), options), CameraInterface.getInstance().getmCameraId(), cameraOrientation);
//        Bitmap bitmap = BitmapUtils.rotateBitmap(BitmapFactory.decodeFile(pictureFile.getPath(), options), 45);
//        Bitmap waterBitmap = WaterMaskUtils.drawTextToRightBottom(this, bitmap, "waterMaskTest123", 16, Color.RED, 0, 0);
//        Bitmap smallBitmap = BitmapUtils.bitmapCompress(bitmap, 120);
        if (pictureSize > 0) {
            bitmap = BitmapUtils.bitmapCompress(bitmap, 120);
        }
//        bitmap = BitmapUtils.compressToSizeByQuality(bitmap, 120);
        Log.i(TAG, "onTakePictureSuccess bitmap.getWidth: " + bitmap.getWidth() + ", bitmap.getHeight():" + bitmap.getHeight());
        Log.i(TAG, "onTakePictureSuccess picQuality: " + picQuality + ", bitmap.getByteCount():" + bitmap.getByteCount());
//        Log.d(TAG, "onTakePictureSuccess picQuality: " + picQuality + ", smallBitmap.getByteCount():" + smallBitmap.getByteCount());
        BitmapUtils.saveBitmapToSd(bitmap, pictureFile.getPath(), picQuality);

        //更新本地相册
        Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(pictureFile));
        sendBroadcast(localIntent);
        Log.i(TAG, "拍照成功 pictureFile:" + pictureFile.getPath());

        showDefaultDialog();
        CompressImg(pictureFile);
//        Intent intent = new Intent();
//        intent.putExtra(CameraParaUtil.picturePath, pictureFile.getPath());
//        setResult(Activity.RESULT_OK, intent);
//        finish();
    }


    private void CompressImg(File loadFile) {
        Luban.with(this)
                .load(loadFile)
                .ignoreBy(100)
                .setTargetDir(rootPath)
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        LogUtils.write("start");
                    }

                    @Override
                    public void onSuccess(File file) {
                        String path = file.getPath();
                        LogUtils.write("FilePath:" + path);
                        uploadFile(file);
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.write(e.getMessage());
                    }
                }).launch();
    }


    private void uploadFile(File imgFile) {
        if (uploadType.equals("ocr_car")) {
            mPresent.uploadOCRCar(imgFile, new UploadCallBack() {
                @Override
                public void uploadFinish(String netaddress) {
                    ToastUtils.showToastShort(netaddress);
                    hideDefaultDialog();
                    Intent mintent = new Intent();
                    mintent.putExtra("value", netaddress);
                    setResult(RESULT_OK, mintent);
                    finish();
//                    WritableMap writableMap = Arguments.createMap();
//                    writableMap.putString("imgs", netaddress);
//                    getCallBack("cgPhotos").invoke(writableMap);
                }

                @Override
                public void uploadFail() {
                    hideDefaultDialog();
//                    WritableMap writableMap = Arguments.createMap();
//                    writableMap.putString("imgs", "");
//                    getCallBack("cgPhotos").invoke(writableMap);
                }
            });
        } else if (uploadType.equals("ocr_person")) {
            mPresent.uploadOCRPerson(imgFile, new UploadCallBack() {
                @Override
                public void uploadFinish(String netaddress) {
                    ToastUtils.showToastShort(netaddress);
                    hideDefaultDialog();
                    Intent mintent = new Intent();
                    mintent.putExtra("value", netaddress);
                    setResult(RESULT_OK, mintent);
                    finish();
//                    WritableMap writableMap = Arguments.createMap();
//                    writableMap.putString("imgs", netaddress);
//                    getCallBack("cgPhotos").invoke(writableMap);
                }

                @Override
                public void uploadFail() {
                    hideDefaultDialog();
//                    WritableMap writableMap = Arguments.createMap();
//                    writableMap.putString("imgs", "");
//                    getCallBack("cgPhotos").invoke(writableMap);
                }
            });
        }
    }


    @Override
    public void onTakePictureFail(byte[] data) {
        Log.e(TAG, "拍照失败，请检查权限设置!"); //三星A8出现无法创建文件夹的提示，重启恢复正常
        CameraParaUtil.pictureBitmap = BitmapUtils.rotateBitmap(BitmapUtils.Bytes2Bitmap(data), CameraInterface.getInstance().getmCameraId(), cameraOrientation);
        Intent intent = new Intent();
        setResult(CameraParaUtil.REQUEST_CODE_FROM_CAMERA_FAIL, intent);
        finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        XPermissionUtils.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
